package com.zhong.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhong.common.core.domain.model.LoginUser;
import com.zhong.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        setTime("createTime",metaObject);
        LoginUser user = null;
        try {
            user = SecurityUtils.getLoginUser();
        }catch (Exception e){}
        if(user!=null){
            setValue("createBy", user.getUsername(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setTime("updateTime",metaObject);
        LoginUser user = null;
        try {
            user = SecurityUtils.getLoginUser();
        }catch (Exception e){}

        if(user!=null){
            setValue("updateBy", user.getUsername(), metaObject);
        }
    }

    private void setValue(String fieldName, Object val, MetaObject metaObject) {
        if (metaObject.hasSetter(fieldName) && val != null) {
            setFieldValByName(fieldName, val, metaObject);
        }
    }

    private void setTime(String fieldName, MetaObject metaObject){
        if (metaObject.hasSetter(fieldName) ) {
            setFieldValByName(fieldName, new Date(), metaObject);
        }
    }

}
